<?php
namespace app\beautiful\logic\order;

use app\beautiful\logic\ApplyServiceLogic;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingIntegralModel;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberProjectModel;
use app\beautiful\model\member\MemberSnapUpModel;
use app\beautiful\model\order\SnapUpOrderModel;
use app\beautiful\model\project\ProjectModel;
use app\beautiful\model\project\SnapUpModel;
use app\common\model\ShopGmvLogsModel;
use app\beautiful\logic\PartnerLogic;
class OrderSnapUpLogic
{
    use OrderTrait;

    protected $order_data = [];
    protected $snap_up;
    protected $project;
    protected $order;
    
    
     //微信支付回调调用
    public function wxPay($params){
        $this->checkOrderPayStatus($params);
        $this->completePayAct('weixin',$params['payinfo']);
        $MemberWalletLogic = new MemberWalletLogic($this->order->shop_id, $this->order->member_id);
        $MemberWalletLogic->addIntegralByPayment($this->order->need_pay); //更新支付返的积分
        //计算业绩
        $PartnerLogic = new PartnerLogic($this->order->shop_id);
        $PartnerLogic->commission($this->order->member_id, $this->order->need_pay);
        //写入GMV
        $shop_gmv_logs = new ShopGmvLogsModel();
        $shop_gmv_logs->shop_id= $this->order->shop_id;
        $shop_gmv_logs->balance= $this->order->need_pay;
        $shop_gmv_logs->save();
    }
    
    public function moneyPay($params)
    {
        //判断订单支付的状态与数据初始化
        $this->checkOrderPayStatus($params);

        //下面是独属于余额支付
        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);
        
        $res = $MemberWalletLogic->useBalance($this->order->need_pay, $this->order->total_price, 14); //商城购物使用
        if($res == false) $this->error($MemberWalletLogic->getError());
      
        //完成支付后的操作
        $this->completePayAct('money');
    }
    
    
    public function createOrder($params)
    {
        //判断用户
        empty($params['member_id']) && $this->error('请先登录后再操作');
        $this->checkMember($params['member_id'], false);
        //判断传来的数量
        $num = (int)$params['num'];
        if ($num <= 0) $this->error('购买数量不能小于0');

        $snap_up_id = (int)$params['snap_up_id'];
        if ($snap_up_id == 0) $this->error('抢购不存在');
        //判断抢购
        $this->checkSnapUp($snap_up_id, true);
        if ($this->snap_up->is_delete != 0) $this->error('抢购不存在');
        if ($this->snap_up->status != 1) $this->error('抢购已下架');
        //判断项目
        $this->checkProject($this->snap_up->project_id);

        //秒杀活动时间内判断数量
        if ($flash_status=$this->checkFlashStatus()) {
            if ($this->snap_up->flash_num < $num) $this->error('秒杀数量不足够');
        }

        //判断总价
        $price = $flash_status ? $this->snap_up->flash_price : ($this->member->level_id == 0 ? $this->project->market_price : $this->snap_up->vip_price);
        $total_price = round(($price * $num * 100) / 100, 2);
        if (empty($params['total_price'])) $this->error('参数错误#1');
        if ((float)$params['total_price'] != $total_price) $this->error('参数错误#2');

        //判断优惠卷
        $coupon_id = $params['coupon_id'] ?? 0;
        $couponBalance = 0;
        if (!empty($coupon_id)) {
            if (null === $myCoupon = MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在');
            if ($myCoupon->status == 1 || $myCoupon->money_limit > $total_price) $this->error('该优惠券不可用');
            if ($myCoupon->member_id != $params['member_id']) $this->error('该优惠券不可用');
            $couponBalance = $myCoupon->coupon_money;
        }

        //判断积分抵扣
        $use_integral = (int)$params['use_integral'];
        if ($use_integral == 1) {
            $integral_balance = $this->getIntegralBalance($total_price);
        }
        $integral = isset($integral_balance) ? $integral_balance['integral'] : 0;
        $balance = isset($integral_balance) ? $integral_balance['balance'] : 0;

        //获取需要支付的金额
        $need_pay = round((($total_price) * 100 - $couponBalance * 100 - $balance * 100) / 100, 2);

        $order_model= new SnapUpOrderModel();
        $order_model->save([
            'shop_id'=>$this->shopId,
            'member_id'=>$this->member->member_id,
            'snap_up_id'=>$this->snap_up->snap_up_id,
            'project_id'=>$this->project->project_id,
            'full_name'=>$this->project->full_name,
            'abbreviation'=>$this->project->abbreviation,
            'valid_time'=>$this->snap_up->valid_time,
            'valid_unit'=>$this->snap_up->valid_unit,
            'is_flash_sale'=>$flash_status ? 1 : 0,
            'market_price'=>$this->project->market_price,
            'price'=>$price,
            'cover_img'=>$this->project->cover_img,
            'total_num'=>$num,
            'total_price'=>$total_price,
            'member_coupon_id'=>$params['coupon_id'],
            'coupon_money'=>$couponBalance,
            'use_integral'=>$integral,
            'integral_balance'=>$balance,
            'need_pay'=>$need_pay,
        ]);

        if($flash_status){
            $this->snap_up->flash_num=$this->snap_up->flash_num-$num;
            $this->snap_up->fictitious_take_count=$this->snap_up->fictitious_take_count+$num;
            $this->snap_up->take_count=$this->snap_up->take_count+$num;
            $this->snap_up->save();

            $this->project->take_count = $this->project->take_count + $num;
            $this->project->save();
        }
        return $order_model->snap_up_order_id;
    }
    
   

    public function cancelOrder($params)
    {
        //判断用户
        empty($params['member_id']) && $this->error('请先登录后再操作');
        $this->checkMember($params['member_id'], false);

        //判断传来的订单
        $snap_up_order_id = (int)$params['snap_up_order_id'];
        $this->checkOrder($snap_up_order_id, true);
        if ($this->order->member_id != $this->member->member_id) $this->error('订单不存在');
        if ($this->order->is_paid != 0) $this->error('订单不存在');
        if ($this->order->is_delete == 1) $this->error('订单不在未支付状态');

        //判断抢购
        $this->checkSnapUp($this->order->snap_up_id,true);

        //判断项目
        $this->checkProject($this->snap_up->project_id);

        //处理订单
        $this->order->is_delete = 1;
        $this->order->save();

        //如果是秒杀取消就释放库存
        if($this->order->is_flash_sale==1){
            $num=$this->order->total_num;
            $this->snap_up->flash_num=$this->snap_up->flash_num+$num;
            $this->snap_up->fictitious_take_count=$this->snap_up->fictitious_take_count-$num > 0 ? $this->snap_up->fictitious_take_count-$num : 0;
            $this->snap_up->take_count=$this->snap_up->take_count-$num;
            $this->snap_up->save();

            $this->project->take_count = $this->project->take_count - $num;
            $this->project->save();
        }

    }

    protected function completePayAct($type,$payinfo = [])
    {
        $this->order->is_paid = 1;
        $this->order->is_delete = 1;
        $this->order->pay_time = time();
        $this->order->pay_type = $type;
        $this->order->pay_info = $payinfo;
        $this->order->save();

        //如果不是秒杀这时候要去添加销量
        if($this->order->is_flash_sale==0){
            $num = $this->order->total_num;
            $this->snap_up->fictitious_take_count=$this->snap_up->fictitious_take_count+$num;
            $this->snap_up->take_count=$this->snap_up->take_count+$num;
            $this->snap_up->save();

            $this->project->take_count = $this->project->take_count + $num;
            $this->project->save();
        }

        //计算有有效时间
        if($this->order->valid_unit=='day') $valid_unit=86400;
        if($this->order->valid_unit=='month') $valid_unit=86400*30;
        if($this->order->valid_unit=='year') $valid_unit=86400*365;
        $valid_end_time=date("Y-m-d",time()+($valid_unit*$this->order->valid_time));


        //处理我的抢购
        $member_sanp_up_data=[
            'shop_id'=>$this->shopId,
            'member_id'=>$this->member->member_id,
            'snap_up_order_id'=>$this->order->snap_up_order_id,
            'snap_up_id'=>$this->snap_up->snap_up_id,
            'project_id'=>$this->project->project_id,
            'full_name'=>$this->order->full_name,
            'abbreviation'=>$this->order->abbreviation,
            'valid_end_time'=>$valid_end_time,
            'market_price'=>$this->order->market_price,
            'price'=>$this->order->price,
            'cover_img'=>$this->order->cover_img,
            'total_num'=>$this->order->total_num,
            'remain_num'=>$this->order->total_num,
            'total_price'=>$this->order->total_price,
            'member_coupon_id'=>$this->order->member_coupon_id,
            'coupon_money'=>$this->order->coupon_money,
            'use_integral'=>$this->order->use_integral,
            'integral_balance'=>$this->order->integral_balance,
            'youhui_balance'=>$this->order->youhui_balance,
            'need_pay'=>$this->order->need_pay,
            'pay_type'=>$this->order->pay_type,
            'pay_time'=>$this->order->pay_time,
            'pay_info'=>$this->order->pay_info,
        ];
        $member_snap_up_model=new MemberSnapUpModel();
        $member_snap_up_model->save($member_sanp_up_data);

        //处理我的项目
        $member_project_data=[
            'shop_id'=>$this->shopId,
            'member_id'=>$this->member->member_id,
            'source'=>'snap_up',
            'project_id'=>$this->project->project_id,
            'member_snap_up_id'=>$member_snap_up_model->member_snap_up_id,
            'total_num'=>$this->order->total_num,
            'remain_num'=>$this->order->total_num,
            'valid_end_time'=>$valid_end_time,
        ];

        $member_project_model=new MemberProjectModel();
        $member_project_model->save($member_project_data);

        //添加办卡记录
        $res=ApplyServiceLogic::apply($this->shopId,$this->member->member_id,'snap_up',$this->order->abbreviation,$member_snap_up_model->member_snap_up_id,$this->order->need_pay,$this->order->total_price,0,0);
        if(!$res) $this->error('支付失败');
    }

    protected function checkOrderPayStatus($params)
    {
        //判断用户
        empty($params['member_id']) && $this->error('请先登录后再操作');
        $this->checkMember($params['member_id'], false);

        //判断传来的订单
        $snap_up_order_id = (int)$params['snap_up_order_id'];
        $this->checkOrder($snap_up_order_id, true);
        if ($this->order->member_id != $this->member->member_id) $this->error('订单不存在');
        if ($this->order->is_paid != 0) $this->error('订单不存在');
        if ($this->order->is_delete == 1) $this->error('订单不在未支付状态');
        if($this->order->add_time < (time() - 900)) $this->error('订单支付已经超时了，不能继续支付');

        //判断抢购
        $this->checkSnapUp($this->order->snap_up_id,true);

        //判断项目
        $this->checkProject($this->snap_up->project_id);

        //处理数据
        if(!empty($this->order->member_coupon_id)){
            if(null === $myCoupon = MemberCouponModel::find($this->order->member_coupon_id)) $this->error('优惠券不存在');
            if($myCoupon->status == 1) $this->error('优惠券不存在');

            $myCoupon->status = 1;
            $myCoupon->save();
            LogsLogic::coupon($this->shopId, $this->member->member_id, -1, 14, $this->order->member_coupon_id, '', 0);
        }
        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);
        if(!empty($this->order->use_integral)){ //使用积分
            $res = $MemberWalletLogic->useIntegral($this->order->use_integral, 11);
            if($res == false) $this->error($MemberWalletLogic->getError());
        }
        $needPay = round(($this->order->total_price * 100 - $this->order->coupon_money * 100 - $this->order->integral_balance * 100)/100,2);
        if($needPay <= 0 or $needPay!=$this->order->need_pay)  $this->error('支付金额不正确');
    }


    protected function checkSnapUp($snap_up_id, $lock)
    {
        if (null === $this->snap_up = SnapUpModel::lock($lock)->find($snap_up_id)) $this->error('抢购不存在');
        if ($this->snap_up->shop_id != $this->shopId) $this->error('抢购不存在');
    }

    protected function checkProject($project_id)
    {
        if (null === $this->project = ProjectModel::find($project_id)) $this->error('项目不存在');
        if ($this->project->shop_id != $this->shopId) $this->error('项目不存在');
    }

    protected function checkOrder($snap_up_order_id,$lock)
    {
        if(null === $this->order = SnapUpOrderModel::lock($lock)->find($snap_up_order_id))  $this->error('订单不存在');
        if($this->order->shop_id != $this->shopId) $this->error('订单不存在');
    }

    protected function checkFlashStatus()
    {
        return ($this->snap_up->is_flash_sale == 1 && $this->snap_up->is_flash_sale_expire == 0);
    }


    public function getIntegralBalance($total_price)
    {
        $SettingBalance = SettingBalanceModel::where([['shop_id', '=', $this->shopId]])->find();
        if (null === $SettingBalance) {
            $integral_deduction_balance_limit_rate = 0;
        } else {
            $integral_deduction_balance_limit_rate = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比
        }
        $integralSetting = SettingIntegralModel::where([['shop_id', '=', $this->shopId]])->find();
        if ($integralSetting === null) { //如果是空 代表不使用积分抵扣余额
            $integral_exchange_balance = 0;
        } else {
            $integral_exchange_balance = $integralSetting->integral_exchange_balance;//汇率
        }

        $pre_can_exchange_balance = round(($total_price * ($integral_deduction_balance_limit_rate * 100)) / 10000, 2);
        $pre_can_exchange_integral = $integral_exchange_balance == 0 ? 0 : round(($pre_can_exchange_balance * 10000) / ($integral_exchange_balance * 100), 0);
        $member_integral = $this->member->integral;
        if ($member_integral >= $pre_can_exchange_integral) {
            $return = [
                'integral' => $pre_can_exchange_integral,
                'balance' => $pre_can_exchange_balance
            ];
        } else {
            $return = [
                'integral' => $member_integral,
                'balance' => round(($member_integral * ($integral_exchange_balance * 100)) / 10000, 2),
            ];
        }
        return $return;

    }
}